package com.kyxx.topics.fragment;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.MainActivity;
import com.kyxx.topics.R;
import com.kyxx.topics.activity.DetailActivity;
import com.kyxx.topics.activity.EditTagActivity;
import com.kyxx.topics.activity.UserLoginActivity2;
import com.kyxx.topics.adapter.MainTabFragmentAdapter;
import com.kyxx.topics.bean.ArticleBean;
import com.kyxx.topics.bean.TagBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.SizeUtils;
import com.kyxx.topics.utils.TextUtil;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.widget.BannerViewPagerNew;
import com.kyxx.topics.widget.CusPtrClassicFrameLayout;
import com.kyxx.topics.widget.HeaderViewPagerFragment;
import com.kyxx.topics.widget.MyHeaderViewPager;
import com.kyxx.topics.widget.MyViewPager;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.widget.HeaderViewPager;
import com.lzy.widget.loop.LoopViewPager;
import com.lzy.widget.tab.CircleIndicator;
import com.lzy.widget.tab.PagerSlidingTabStrip;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.Response;

public class MainFragment2 extends Fragment {
    private LinearLayout top_bar_main;
    private ImageView iv_edit;
    private TabLayout tl;
    RelativeLayout rl;
    private CusPtrClassicFrameLayout ptrv;
    public List<HeaderViewPagerFragment> fragments = new ArrayList<>();
    private BannerViewPagerNew pagerHeader;
    MyViewPager viewPager;

    private MyHeaderViewPager scrollableLayout;
    private me.relex.circleindicator.CircleIndicator ci;
    PagerSlidingTabStrip tabs;
    private List<TagBean> tagBeanList = new ArrayList<>();
    private List<TagBean> tagBeanListNo = new ArrayList<>();
    private List<ArticleBean> articleBeanListBanner = new ArrayList<>();
    public String[] images;
    public String[] titles;
    private int pageSize = 1;
    private int countSize = 10;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisk(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .showImageOnFail(R.mipmap.image_default)
            .showImageOnLoading(R.mipmap.image_default)
            .showImageForEmptyUri(R.mipmap.image_default)
            .build();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.REFRESH:
                    ptrv.refreshComplete();
                    break;
            }
        }
    };

    public static MainFragment2 newInstace(Bundle args) {
        MainFragment2 f = new MainFragment2();
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main2, container, false);
        top_bar_main = (LinearLayout) view.findViewById(R.id.top_bar_main);
        iv_edit = (ImageView) view.findViewById(R.id.iv_edit);
        tl = (TabLayout) view.findViewById(R.id.tl);
        pagerHeader = (BannerViewPagerNew) view.findViewById(R.id.pagerHeader);
        rl = (RelativeLayout) view.findViewById(R.id.rl);
        ci = (me.relex.circleindicator.CircleIndicator) view.findViewById(R.id.ci);
        tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
        viewPager = (MyViewPager) view.findViewById(R.id.viewPager);
        scrollableLayout = (MyHeaderViewPager) view.findViewById(R.id.scrollableLayout);
        ptrv = (CusPtrClassicFrameLayout) view.findViewById(R.id.ptrv);
        ptrv.setMode(PtrFrameLayout.Mode.REFRESH);
        ptrv.setLastUpdateTimeHeaderRelateObject(getActivity());
//        pagerHeader.setNestParent(ptrv);

        scrollableLayout.setOnScrollListener(new MyHeaderViewPager.OnScrollListener() {
            @Override
            public void onScroll(int currentY, int maxY) {
                if (scrollableLayout.isHeadTop()) {
                    ptrv.setPtrHandler(new PtrDefaultHandler() {
                        @Override
                        public void onRefreshBegin(PtrFrameLayout frame) {
                            if (fragments.size() > 0) {
                                if (viewPager.getCurrentItem() == 0) {
                                    ((TopicFragmentNew) fragments.get(0)).initListView(Constants.REFRESH, pageSize, countSize);
                                } else {
                                    ((NewsFragmentNew) fragments.get(viewPager.getCurrentItem())).initList(Constants.REFRESH, pageSize, countSize);
                                }
                                getBanner();
                            } else {
                                ptrv.refreshComplete();
                            }
                        }

                        @Override
                        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                            return super.checkCanDoRefresh(frame, content, header);
                        }
                    });
                } else {
                    ptrv.setPtrHandler(null);
                }
            }

            @Override
            public void stopScroll() {
                viewPager.setNoScroll(false);
            }

            @Override
            public void onScrollUp() {
                viewPager.setNoScroll(true);
            }
        });
        iv_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(BaseApp.getModel().getId())) {
                    startActivity(new Intent(getActivity(), UserLoginActivity2.class));
                    return;
                }
                Intent intent = new Intent(getActivity(), EditTagActivity.class);
                intent.putExtra("tagBeanList", (Serializable) tagBeanList);
                intent.putExtra("tagBeanListNo", (Serializable) tagBeanListNo);
                startActivityForResult(intent, 1);
            }
        });
        initTag();
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<HeaderViewPagerFragment> fragments0 = new ArrayList<>();
        if (requestCode == 1 && resultCode == 47) {
//            getActivity().finish();
//            getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
//            tagBeanList = (ArrayList<TagBean>) data.getSerializableExtra("tagBeanList");
//            tagBeanListNo = (ArrayList<TagBean>) data.getSerializableExtra("tagBeanListNo");
//            if (tagSize > tagBeanList.size()) {
//                int r = tagSize - tagBeanList.size();
//                for (int i = 0; i < r; i++) {
//                    fragments.remove(fragments.size() - 1);
//                }
//            } else if (tagSize < tagBeanList.size()) {
//                int r = tagBeanList.size() - tagSize;
//                for (int i = 0; i < r; i++) {
//                    fragments.add(new NewsFragmentNew());
//                }
//            }
//            tagSize = tagBeanList.size();
//            for (int i = 1; i < fragments.size(); i++) {
//                ((NewsFragmentNew) fragments.get(i)).setValue(tagBeanList.get(i));
//            }
//            final MainTabFragmentAdapter tabFragmentAdapter = new MainTabFragmentAdapter(fragments, tagBeanList, getChildFragmentManager(), getActivity());
//            viewPager.setAdapter(tabFragmentAdapter);
//            tl.setupWithViewPager(viewPager);
//            scrollableLayout.setCurrentScrollableContainer(fragments.get(0));
//            viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//                @Override
//                public void onPageSelected(int position) {
//                    scrollableLayout.setCurrentScrollableContainer(fragments.get(position));
//                }
//            });
            ((MainActivity) getActivity()).replaceFragment0();
        }
    }

    private void initTag() {
        HttpParams params = new HttpParams();
        params.put("uid", BaseApp.getModel().getId());
        OkGoRequest.post(UrlUtils.GETTAGS, getActivity(), "gettags", CacheMode.REQUEST_FAILED_READ_CACHE, params, new StringCallback() {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                ptrv.setVisibility(View.GONE);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject result = new JSONObject(s);
                    try {
                        tagBeanList = JSON.parseArray(result.getJSONObject("data").getJSONArray("tags").toString(), TagBean.class);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        tagBeanList = JSON.parseArray(result.getJSONObject("data").getJSONArray("yes").toString(), TagBean.class);
                    }
                    getBanner();
                    initFragment();
                    tagBeanListNo = JSON.parseArray(result.getJSONObject("data").getJSONArray("no").toString(), TagBean.class);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


//        OkGoRequest.get(UrlUtils.GETCATE, getActivity(), "getcate", CacheMode.REQUEST_FAILED_READ_CACHE, new StringCallback() {
//            @Override
//            public void onCacheSuccess(String s, Call call) {
//                super.onCacheSuccess(s, call);
//                onSuccess(s, call, null);
//            }
//
//            @Override
//            public void onSuccess(String s, Call call, Response response) {
//                try {
//                    JSONObject result = new JSONObject(s);
//                    tagBeanList = JSON.parseArray(result.getJSONArray("data").toString(), TagBean.class);
//                    getBanner();
//                    initFragment();
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }

    private void getBanner() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("cat", tagBeanList.get(0).getId());
        String cacheKey = "slidelist&cat=" + tagBeanList.get(0).getId();
        OkGoRequest.post(UrlUtils.SLIDELIST, getActivity(), cacheKey, CacheMode.REQUEST_FAILED_READ_CACHE, httpParams, new StringCallback() {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject result = new JSONObject(s);
                    articleBeanListBanner = JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class);
                    images = new String[articleBeanListBanner.size()];
                    for (int i = 0; i < articleBeanListBanner.size(); i++) {
                        if (TextUtils.isEmpty(articleBeanListBanner.get(i).getImgurl().getPath())) {
                            images[i] = UrlUtils.BASEHTTP + "";
                        } else {
                            images[i] = UrlUtils.BASEHTTP + articleBeanListBanner.get(i).getImgurl().getPath();
                        }
                    }
                    pagerHeader.setAdapter(new HeaderAdapter());
                    ci.setViewPager(pagerHeader);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 内容页的适配器
     */
    private class ContentAdapter extends FragmentPagerAdapter {

        public ContentAdapter(FragmentManager fm) {
            super(fm);
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return tagBeanList.get(position).getTitle();
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    /**
     * 头布局的适配器
     */
    private class HeaderAdapter extends PagerAdapter {

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), DetailActivity.class);
                    intent.putExtra("id", articleBeanListBanner.get(position).getId());
                    intent.putExtra("title", articleBeanListBanner.get(position).getTitle());
                    startActivity(intent);
                }
            });
            imageLoader.displayImage(images[position], imageView, options);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return images.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    private void initFragment() {
        fragments.clear();
        Bundle args0 = new Bundle();
        args0.putSerializable("tagBean", tagBeanList.get(0));
        TopicFragmentNew topicFragmentNew = TopicFragmentNew.newInstace(args0);
        topicFragmentNew.setHandler(handler);
        fragments.add(topicFragmentNew);

//        TopicFragmentNew topicFragment = new TopicFragmentNew();
//        topicFragment.setValue(tagBeanList.get(0));
//        topicFragment.setHandler(handler);
//        fragments.add(topicFragment);
        for (int i = 1; i < tagBeanList.size(); i++) {
            Bundle args = new Bundle();
            args.putSerializable("tagBean", tagBeanList.get(i));
            NewsFragmentNew newsFragmentNew = NewsFragmentNew.newInstace(args);
            newsFragmentNew.setHandler(handler);
            fragments.add(newsFragmentNew);
//            NewsFragmentNew newsFragment = new NewsFragmentNew();
//            newsFragment.setValue(tagBeanList.get(i));
//            newsFragment.setHandler(handler);
//            fragments.add(newsFragment);
        }
//        viewPager.setAdapter(new ContentAdapter(getActivity().getSupportFragmentManager()));
//        tabs.setViewPager(viewPager);
        final MainTabFragmentAdapter tabFragmentAdapter = new MainTabFragmentAdapter(fragments, tagBeanList, getChildFragmentManager(), getActivity());
        viewPager.setAdapter(tabFragmentAdapter);
        tl.setupWithViewPager(viewPager);
        scrollableLayout.setCurrentScrollableContainer(fragments.get(0));
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                scrollableLayout.setCurrentScrollableContainer(fragments.get(position));
            }
        });
    }

    private void outAnim() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(top_bar_main, "translationY", -100f);
        animator.setDuration(500);
        animator.start();
    }

    private void inAnim() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(top_bar_main, "translationY", 0f);
        animator.setDuration(500);
        animator.start();
    }
}
